const express = require("express");
const router = express.Router();
const { User } = require("../../models");
const { success, failure } = require("../../utils/response");
const {NotFound} = require('http-errors');
const { Op } = require("sequelize");

// 分页查询全部人员数据
router.get("/", async (req, res) => {
  try {
    const query = req.query;

    const pageIndex = Math.abs(Number(query.pageIndex)) || 1;
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    const offset = (pageIndex - 1) * pageSize;

    const condition = {
      order: [["id", "DESC"]],
      limit: pageSize,
      offset,
    };

    const { count, rows } = await User.findAndCountAll(condition);
    success(res, "人员查询成功", {
      pagination: {
        total: count,
        pageIndex,
        pageSize,
      },
      data: rows,
    });
  } catch (error) {
    failure(res, error);
  }
});

// 模糊查询
router.get("/search",async(req,res)=>{
    try {
        const query = req.query
        
        const pageIndex = Math.abs(Number(query.pageIndex)) || 1
        const pageSize = Math.abs(Number(query.pageSize)) ||10
        const offset = (pageIndex -1) * pageSize

        const condition = {
            where:{},
            order:[["id","DESC"]],
            limit:pageSize,
            offset
        }
        if(query.email){
            condition.where.email = query.email
            // condition.where = {
            //     email:{
            //         [Op.eq]:query.email
            //     }
            // }
        }
        if(query.username){
            condition.where.username = query.username
            // condition.where = {
            //     username:{
            //         [Op.eq]:query.username
            //     }
            // }
        }
        if(query.nickname){
            condition.where.nickname = {
              [Op.like]: `%${query.nickname}%`
            }
            // condition.where = {
            //     nickname:{
            //         [Op.like]:`%${query.nickname}%`
            //     }
            // }
        }
        if(query.role){
          condition.where.role = query.role;
            // condition.where = {
            //     role:{
            //         [Op.eq]:query.role
            //     }
            // }
        }
        const {count,rows} = await User.findAndCountAll(condition)
        success(res,"查询成功",{
            pagination:{
                total:count,
                pageIndex,
                pageSize
            },
            data:rows
        })
    } catch (error) {
        failure(res,error)
    }
})

// 查询当前登录的用户详情
router.get("/me",async(req,res)=>{
  try {
    const user = req.user;
    success(res,'查询当前用户信息成功',{user})
  } catch (error) {
    failure(res,error)
  }
})

// 获取人员详情
router.get("/:id", async (req, res) => {
  try {
    const user = await getUser(req);
    success(res, "人员详情查询成功！", { user });
  } catch (error) {
    failure(res, error);
  }
});

// 新增人员
router.post("/", async (req, res) => {
  try {
    const body = filterBody(req);
    const user = await User.create(body);
    success(res, "新增人员成功！", { user });
  } catch (error) {
    failure(res, error);
  }
});

// 修改人员详情
router.put("/:id", async (req, res) => {
  try {
    const body = filterBody(req);
    const user = getUser(req);
    await user.updated(body);
    success(res, "修改信息成功！", { user });
  } catch (error) {
    failure(res, error);
  }
});

// 删除人员
router.delete("/:id",async(req,res)=>{
    try {
        const user = await getUser(req)
        await user.destroy()
        success(res,"删除成功！")
    } catch (error) {
        failure(res,error)
    }
})


/**
 * 公共方法：参数过滤
 * @param {*} req 
 * @returns 
 */
function filterBody(req) {
  const {
    email,
    username,
    password,
    nickname,
    sex,
    avatar,
    company,
    introduce,
    role,
  } = req.body;
  return {
    email,
    username,
    password,
    nickname,
    sex,
    avatar,
    company,
    introduce,
    role,
  };
}

/**
 * 公共方法：获取人员
 * @param {*} req
 * @returns
 */
async function getUser(req) {
  const { id } = req.params;
  const condition = [
    {
      model:User,
      as:"users"
    }
  ]
  const user = await User.findByPk(id,condition);
  if (!user) {
    throw new NotFound("未查找到当前人员！");
  }
  return user;
}

module.exports = router;
